<?php

// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\goods;

use app\common\model\Goods;
use app\common\model\GoodsCategory;
use app\common\model\GoodsContentManager;
use app\service\goods\ContentService;
use app\service\goods\TextContentService;
use think\facade\Db;
use app\common\model\GoodsTag;
use app\common\model\GoodsTagRelation;
use app\common\model\GoodsComment;

class GoodService
{
    /**
     * 获取商品列表
     */
    public function getGoodsList($where = [], $limit = 15)
    {
        try {
            $list = Goods::with(['category', 'tags'])
                ->withSearch(array_keys($where), $where)
                ->order("sort desc, id desc")
                ->paginate($limit)
                ->each(function ($item) {
                    $item->cate_name         = $item?->category?->name;
                    $item->paid_content_type = $item?->goodsContent?->type;
                    // 添加标签文字数组
                    $tagNames = [];
                    if ($item->tags) {
                        foreach ($item->tags as $tag) {
                            $tagNames[] = $tag->name;
                        }
                    }
                    $item->tags = $tagNames;
                    // 商品首图
                    $item->image = $item->slider_image ? $item->slider_image[0] : '';
                });

            return $list;
        } catch (\Exception $e) {
            throw new \Exception('获取商品列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取商品详情
     */
    public function getGoodDetail($id)
    {
        try {
            $good = Goods::find($id);

            if (!$good) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 加载内容
            $goodsContent            = GoodsContentManager::where('goods_id', $id)->find();
            $good->paid_content_type = $goodsContent ? $goodsContent->type : 'text';

            // 规格信息
            $specService     = new SpecService();
            $good->spec_data = $specService->getGoodsSpecInfo($id);

            // 商品标签 - 返回标签文字数组
            $tagNames = [];
            $goodTags = $good->tags()->select();
            foreach ($goodTags as $tag) {
                $tagNames[] = $tag->getData('name');
            }
            $good->tags = $tagNames;

            return $good;
        } catch (\Exception $e) {
            throw new \Exception('获取商品详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 添加商品
     */
    public function addGood($data)
    {

        // 验证必填字段
        if (empty($data['name'])) {
            throw new \Exception('商品名称不能为空');
        }

        if (empty($data['cate_id'])) {
            throw new \Exception('商品分类不能为空');
        }

        // 验证分类
        $this->validateCategory($data['cate_id']);


        $data = hook('good_add_before', $data, 'filter');

        // 提取规格数据
        $spec_data = $data['spec_data'] ?? [];
        unset($data['spec_data']);

        // 提取标签数据
        $tags = $data['tags'] ?? [];
        unset($data['tags']);

        // 提取付费内容数据
        $paid_content_type = $data['paid_content_type'] ? $data['paid_content_type'] : 'text';
        unset($data['paid_content_type']);

        // 设置状态
        $data['status'] = 1;

        // 排序为空时 自动排序
        if (empty($data['sort'])) {
            $data['sort'] = Goods::max('sort') + 1;
        }

        // 创建商品
        $good = Goods::create($data);

        // 保存付费内容附表
        $contentService = new ContentService();
        $contentService->saveGoodsPaidContent($good->id, $paid_content_type, []);

        // 保存规格信息
        if (!empty($spec_data)) {
            $specService = new SpecService();
            $specService->saveGoodsSpec($good->id, $spec_data);
        }

        // 处理标签
        if (!empty($tags)) {
            $this->handleGoodsTags($good, $tags);
        }

        return $good;
    }

    /**
     * 编辑商品
     */
    public function editGood($id, $data)
    {

        // 获取商品
        $good = Goods::find($id);

        if (!$good) {
            throw new \Exception(trans('goods_not_exists'));
        }

        // 验证分类
        $this->validateCategory($data['cate_id']);

        $data = hook('good.edit.before', $data, 'filter');

        // 价格检查
        if ($data['price'] < 0) {
            throw new \Exception('商品价格不能为负数');
        }

        // 提取规格数据
        $spec_data = $data['spec_data'] ?? [];
        unset($data['spec_data']);

        // 提取标签数据
        $tags = $data['tags'] ?? [];
        unset($data['tags']);

        // 提取付费内容数据
        $paid_content_type = $data['paid_content_type'] ?? 'text';

        // 更新商品
        $good->save($data);

        // 保存付费内容附表
        $contentService = new ContentService();
        $contentService->saveGoodsPaidContent($good->id, $paid_content_type, []);
        // 保存规格信息
        $specService = new SpecService();
        $specService->saveGoodsSpec($id, $spec_data);

        // 处理标签
        $this->handleGoodsTags($good, $tags);
        return $good;
    }

    /**
     * 删除商品
     */
    public function deleteGood($id)
    {
        // 开始事务
        Db::startTrans();
        try {
            $good = Goods::find($id);

            if (!$good) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 获取商品内容类型
            $goodsContent = GoodsContentManager::where('goods_id', $id)->find();
            $contentType  = $goodsContent ? $goodsContent->type : '';

            // 删除商品相关内容
            if ($contentType) {
                // 删除普通内容
                $contentService = new ContentService();

                // 如果是文本章节类型，需要删除文件系统中的文本文件
                if (in_array($contentType, ['text_chapter', 'text_groups'])) {
                    $textContentService = new TextContentService();
                    $textContentService->deleteGoodsAllChapterTexts($id, $good->cate_id);
                }
            }

            // 删除商品记录
            $good->delete();
            // 删除商品标签
            GoodsTagRelation::where('goods_id', $id)->delete();
            // 删除商品评论
            GoodsComment::where('goods_id', $id)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('删除商品失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新商品状态
     */
    public function updateGoodStatus($id)
    {
        try {
            $good = Goods::find($id);

            if (!$good) {
                throw new \Exception(trans('goods_not_exists'));
            }

            $good->status = $good->status ? 0 : 1;

            return $good->save();
        } catch (\Exception $e) {
            throw new \Exception('更新商品状态失败: ' . $e->getMessage());
        }
    }

    /**
     * 验证分类
     */
    private function validateCategory($cate_id)
    {
        $category = GoodsCategory::where(['id' => $cate_id])->find();

        if (!$category) {
            throw new \Exception('分类不存在');
        }

        return $category;
    }

    /**
     * 处理商品标签
     * @param mixed $goods 商品对象
     * @param array $tags 标签文字数组
     */
    private function handleGoodsTags($goods, $tags)
    {
        if (empty($tags) || !is_array($tags)) {
            // 如果没有标签，清除所有关联
            $goods->tags()->detach();
            return;
        }

        $tagIds = [];
        foreach ($tags as $tagName) {
            $tagName = trim($tagName);
            if (empty($tagName)) {
                continue;
            }

            // 检查标签是否存在，不存在则创建
            $tag = GoodsTag::where('name', $tagName)->find();
            if (!$tag) {
                $tag = GoodsTag::create([
                    'name'   => $tagName,
                    'sort'   => 100,
                    'status' => 1
                ]);
            }
            $tagIds[] = $tag->id;
        }

        // 更新商品标签关联
        // 先删除原有关联
        GoodsTagRelation::where('goods_id', $goods->id)->delete();

        // 添加新关联
        if (!empty($tagIds)) {
            foreach ($tagIds as $tagId) {
                GoodsTagRelation::create([
                    'goods_id' => $goods->id,
                    'tag_id'   => $tagId
                ]);
            }
        }
    }

    /**
     * 获取商品详情页可用的模板列表
     * @return array 模板列表
     */
    public function getGoodsTemplateList()
    {
        // 使用默认模板
        $currentTemplate = config('site.theme.template', 'default');

        // 模板目录路径
        $templatePath = base_path() . '/app/web/view/' . $currentTemplate . '/goods/detail/';
        // 获取所有detail-*.html文件
        $templates = [];

        if (is_dir($templatePath)) {
            $files = scandir($templatePath);
            foreach ($files as $file) {
                if (preg_match('/^detail-(.+)\.html$/', $file, $matches)) {
                    $templateKey  = 'goods/detail/' . str_replace('.html', '', $file);
                    $templateName = ucfirst(str_replace('-', ' ', $matches[1]));

                    $templates[] = [
                        'value' => $templateKey,
                        'label' => $templateName . ' 模板'
                    ];
                }
            }
        }

        // 如果没有找到模板，至少返回默认模板
        if (empty($templates)) {
            $templates[] = [
                'value' => 'goods/detail/detail-index',
                'label' => '默认模板'
            ];
        }

        return $templates;
    }
}